package com.eliza.music.compoment.music

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.collectIsDraggedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.Star
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.blur
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.eliza.library.utils.compose.ImageBuild
import com.eliza.music.model.entity.BasicInfo
import com.eliza.music.model.entity.Category
import com.eliza.music.model.entity.Song
import com.eliza.music.model.tmp.PlaylistList
import com.eliza.music.model.tmp.PlaylistListBig
import com.eliza.music.model.tmp.TempSongLists
import com.eliza.music.ui.pager.DotIndicators
import com.eliza.music.ui.theme.FontSize
import com.eliza.music.ui.theme.PaddingSize
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


@Preview(showBackground = true, showSystemUi = true, backgroundColor = 0xffffffff)
@Composable
private fun SongInPlayListPreview() {
    Column {
        SongView.ItemList(PlaylistListBig.subList(0, PlaylistListBig.size / 4))
        SongView.BigSongCardItem(PlaylistList.first())
        SongView.ItemInPlayList(data = TempSongLists.subList(0, TempSongLists.size % 4))
    }

}


object SongView {

    @Composable
    fun <T : BasicInfo> ItemInList(it: T, modifier: Modifier = Modifier) {
        Row(
            modifier = Modifier
                .height(PaddingSize.Height.size)
                .background(Color.White)
                .padding(PaddingSize.Small.size),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Row(
                modifier = Modifier
                    .weight(0.9f)
                    .background(Color.Transparent),
            ) {
                AsyncImage(
                    model = ImageBuild.CoilImageRequest(
                        LocalContext.current,
                        it.icon
                    ),
                    contentDescription = "",
                    modifier = Modifier
                        .clip(RoundedCornerShape(PaddingSize.Normal.size)),
                    contentScale = ContentScale.Fit
                )

                Column(
                    modifier = Modifier
                        .fillMaxHeight()
                        .padding(10.dp, 0.dp, 0.dp, 0.dp),
                    verticalArrangement = Arrangement.SpaceEvenly,
                ) {
                    Text(
                        text = it.title,
                        fontSize = FontSize.Normal.size,
                        fontWeight = FontWeight.W600,
                        maxLines = 2,
                        color = Color.DarkGray
                    )
                    Text(
                        text = it.description,
                        fontSize = FontSize.Small.size,
                        fontWeight = FontWeight.W900,
                        color = Color.DarkGray.copy(0.6f), maxLines = 1,
                    )
                }

            }
            Icon(
                imageVector = Icons.Rounded.PlayArrow,
                modifier = Modifier
                    .weight(0.1f)
                    .scale(1.2f)
                    .padding(0.dp, 0.dp, 10.dp, 0.dp),
                tint = Color.Gray,
                contentDescription = ""
            )
        }
    }

    @Composable
    fun <T : BasicInfo> ItemList(data: List<T>, modifier: Modifier = Modifier) {
        LazyColumn {
            itemsIndexed(data) { index, it ->
                ItemInList(it, modifier = Modifier.height(40.dp))
            }
        }
    }

    @Composable
    fun <T : BasicInfo> SongListHorizontal(
        data: List<Category<T>>, modifier: Modifier = Modifier
    ) {
        val rememberPagerState = rememberPagerState(pageCount = { data.size })
        HorizontalPager(
            rememberPagerState, modifier = Modifier.width(360.dp)
        ) {
            CategoryView.ItemList(data = data[it], modifier = Modifier.fillMaxWidth(1f))
        }
    }


    @Composable
    fun ItemInPlayList(data: List<Song>, modifier: Modifier = Modifier) {
        LazyColumn {
            itemsIndexed(data) { index, it ->
                SongItemInPlaylist(it, modifier = Modifier.height(40.dp)) {
                    Icon(
                        tint = Color.Gray,
                        imageVector = Icons.Rounded.Close,
                        modifier = Modifier
                            .padding(0.dp, 0.dp, 10.dp, 0.dp)
                            .clickable {
                                data.drop(index)
                            },
                        contentDescription = ""
                    )
                }
            }
        }
    }


    @Composable
    private fun SongItemInPlaylist(
        song: Song,
        modifier: Modifier = Modifier,
        endContent: @Composable() (() -> Unit) = {}
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .background(Color.White)
                .height(40.dp)
                .then(modifier)
                .padding(PaddingSize.Normal.size, 0.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Row(
                modifier = Modifier,
                horizontalArrangement = Arrangement.Start,
                verticalAlignment = Alignment.CenterVertically,
            ) {
                val tt: @Composable (test: String) -> Unit = { it ->
                    Text(
                        text = it,
                        fontSize = 8.sp,
                        fontWeight = FontWeight.W100,
                        color = Color.Red,
                        modifier = Modifier
                            .align(Alignment.CenterVertically)
                            .padding(1.dp, 0.dp)
                            .border(0.2f.dp, Color.Red, RoundedCornerShape(1.dp))
                            .padding(1.dp, 0.dp)
                    )

                }
                if (song.isVip) {
                    tt("VIP")
                }
                if (song.isTemp) {
                    tt("试听")
                }
                Text(
                    modifier = Modifier
                        .fillMaxHeight(0.9f)
                        .padding(PaddingSize.Normal.size),
                    text = buildAnnotatedString {
                        withStyle(
                            style = SpanStyle(
                                fontSize = 16.sp,
                                color = Color.Black
                            )
                        ) {
                            append(song.title)
                        }
                        withStyle(
                            style = SpanStyle(
                                fontWeight = FontWeight.W300,
                                fontSize = FontSize.Small.size,
                                color = Color.Gray
                            )
                        ) {
                            append(" - ")
                            append(song.artist)
                        }
                    }
                )
            }
            endContent()
        }
    }

    @Composable
    fun SongItemInSearch(index: Int, Song: Song, modifier: Modifier = Modifier) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .background(Color.White)
                .then(modifier)
                .padding(PaddingSize.Normal.size, 0.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            var index = index + 1
            val b = index < 4
            Text(
                modifier = Modifier
                    .fillMaxHeight(0.9f)
                    .padding(PaddingSize.Normal.size),
                text = buildAnnotatedString {
                    withStyle(
                        style = SpanStyle(
                            fontSize = 16.sp,
                            color = if (b) Color.Red else Color.Gray
                        )
                    ) {
                        append(index.toString())
                    }
                    append("  ")
                    withStyle(
                        style = SpanStyle(
                            fontSize = 16.sp,
                            color = if (b) Color.Black else Color.Gray,
                            fontWeight = if (b) FontWeight.W400 else FontWeight.W200
                        )
                    ) {
                        append(Song.title)
                    }
                }
            )

            Icon(
                tint = Color.Gray,
                imageVector = Icons.Rounded.Star,
                modifier = Modifier
                    .padding(0.dp, 0.dp, 10.dp, 0.dp)
                    .clickable {

                    },
                contentDescription = ""
            )
        }
    }


    @Composable
    fun <T : BasicInfo> BigSongCardList(
        modifier: Modifier = Modifier,
        data: Category<T>, autoScrollDuration: Long = 2000L,
    ) {
        val scope = rememberCoroutineScope()
        val pagerState = rememberPagerState(pageCount = {
            data.children.size
        })
        val isDragged by pagerState.interactionSource.collectIsDraggedAsState()
        if (isDragged.not()) {
            var intState by remember {
                mutableIntStateOf(0)
            }
            LaunchedEffect(intState) {
                scope.launch {
                    delay(timeMillis = autoScrollDuration)
                    var nextPage = (pagerState.currentPage + 1).mod(pagerState.pageCount)
                    if (nextPage == pagerState.currentPage) {
                        nextPage++
                    }
                    pagerState.animateScrollToPage(nextPage)
                    intState = nextPage
                }
            }
        }
        Box(
            modifier = Modifier
                .then(modifier)
                .heightIn(100.dp, 200.dp)
                .fillMaxWidth()
                .clip(RoundedCornerShape(PaddingSize.Normal.size))
                .background(Color.LightGray),
            contentAlignment = Alignment.BottomStart
        ) {
            HorizontalPager(
                state = pagerState, pageSpacing = 16.dp
            ) {
                BigSongCardItem(data.children[it], modifier)
            }
            DotIndicators(state = pagerState, modifier = Modifier.padding(PaddingSize.Normal.size))
        }
    }

    @Composable
    fun <T : BasicInfo> BigSongCardItem(item: T, modifier: Modifier = Modifier) {
        val screenWidthDp = LocalConfiguration.current.screenWidthDp
        Box(
            modifier = modifier
                .width(screenWidthDp.dp / 2)
                .aspectRatio(0.9f)
                .padding(PaddingSize.Small.size),
            contentAlignment = Alignment.BottomCenter
        ) {
            AsyncImage(
                model = ImageBuild.CoilImageRequest(
                    LocalContext.current,
                    item.icon
                ),
                contentDescription = "",
                modifier = Modifier
                    .fillMaxSize()
                    .align(Alignment.Center)
                    .clip(shape = RoundedCornerShape(10))
                    .blur(30.dp),
                contentScale = ContentScale.FillHeight,
            )
            AsyncImage(
                model = ImageBuild.CoilImageRequest(
                    LocalContext.current,
                    item.icon
                ),
                contentDescription = "",
                modifier = Modifier
                    .align(Alignment.Center)
                    .fillMaxSize(0.5f)
                    .aspectRatio(1f)
                    .clip(shape = RoundedCornerShape(20)),
                contentScale = ContentScale.Crop,
            )
            Text(
                text = item.title.substring(0, 10),
                color = Color.White,
                fontWeight = FontWeight.W700,
                fontSize = FontSize.Large.size,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier
                    .align(Alignment.TopCenter)
                    .padding(0.dp, 15.dp)
            )
            Text(
                text = item.title.substring(0, 20),
                color = Color.White,
                fontWeight = FontWeight.W400,
                fontSize = FontSize.Normal.size,
                minLines = 2,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier
                    .align(Alignment.BottomCenter)
                    .fillMaxWidth()
                    .background(Color.Black.copy(0.2f))
                    .padding(5.dp, 5.dp)
            )
        }
    }
}